﻿using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Profile;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;

namespace AliInfor_Verification_code
{
    public static class AliInfor
    {
        #region 阿里云平台短信服务

        //获取配置文件的授权ID、授权密钥
        public static string aliAccessKeyId = "LTAI5tPyhthnfQk4QuDjvDwH";
        public static string aliAccessKeySecret = "o29qOAjFOtcxD6LKWk1eDu8vc2iGOO";

        /// <summary>
        /// 发送手机短信验证码（阿里云平台）
        /// </summary>
        /// <param name="mobile">接收手机</param>
        /// <param name="signName">短信签名</param>
        /// <param name="tempCode">短信模板ID</param>
        /// <param name="mobileCode">短信验证码</param>
        /// <returns></returns>
        public static bool SendMobileMessageByAli(string mobile, string signName, string tempCode, string mobileCode)
        {
            //拼接读短信目标变量值  "{\"code\":\"1234\"}"
            string tempParam = "{'code" + "':" + mobileCode + "}";// $"code:{mobileCode}";
                                                                  //发送短信并返回结果
            JObject result = SendMessageByAliSms(aliAccessKeyId, aliAccessKeySecret, mobile, signName, tempCode, tempParam);
            //返回代码
            if (result["Code"].ToString().ToLower() == "ok")
            {
                return true;
            }
            else
            {
                return false;
            }

        }

        /// <summary>
        /// 发送手机短信信息（通过阿里云SDK）
        /// </summary>
        /// <param name="aliAccessKey">授权id（阿里云账号的AccessKeyId ）</param>
        /// <param name="aliAccessSecret">授权密钥（阿里云账号的AccessKeySecret）</param>
        /// <param name="phoneNumber">接收手机号（多个用逗号隔开）</param>
        /// <param name="signName">短信签名</param>
        /// <param name="tempCode">短信模板ID</param>
        /// <param name="tempParam">短信模板变量</param>
        /// <returns></returns>
        public static JObject SendMessageByAliSms(string aliAccessKey, string aliAccessSecret, string phoneNumber, string signName, string tempCode, string tempParam)
        {
            //返回结果对象
            JObject result = new JObject();

            //接口文档（里面有sdk）：https://help.aliyun.com/product/44282.html?spm=5176.12226155.0.0.33ac1cbeMfrIwkhttps://home.firefoxchina.cn           
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", aliAccessKey, aliAccessSecret);   //cn-hangzhou： 默认节点
            DefaultAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            request.Method = MethodType.POST;  //请求方式
            request.Domain = "dysmsapi.aliyuncs.com";  //请求域名
            request.Version = "2017-05-25";  //请求版本
            request.Action = "SendSms";  //请求操作
            request.AddQueryParameters("PhoneNumbers", phoneNumber);
            request.AddQueryParameters("SignName", signName);
            request.AddQueryParameters("TemplateCode", tempCode);
            request.AddQueryParameters("TemplateParam", tempParam);
            try
            {
                //发送请求请返回响应
                CommonResponse response = client.GetCommonResponse(request);
                //获取返回的内容
                string content = Encoding.Default.GetString(response.HttpResponse.Content);
                //序列化成对象（Code: 请求状态码，Message：状态码描述，BizId：发送回执ID, RequestId: 请求ID）
                result = (JObject)JsonConvert.DeserializeObject(content);

            }
            catch (ServerException e)
            {
                result.Add("Code", "500");
                result.Add("Message", "短信服务异常：" + e.Message);
            }
            catch (ClientException e)
            {
                result.Add("Code", "501");
                result.Add("Message", "客户端异常：" + e.Message);
            }
            return result;
        }

        #endregion
    }
}
